/*******************************************************************************
 * Package: com.song.boot.springstudy.thread.lock
 * Type:    ReadWriteLock11Day
 * Date:    2022-06-11 21:56
 *
 * 
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.thread.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 功能描述：
 *案例：线程1线程2 读数据（是不是同时读）线程3线程4是写数据（不能同时写，只能排队写）
 * @author Songxianyang
 * @date 2022-06-11 21:56
 */
public class ReadWriteLock11Day {
    /**
     * 主锁
     */
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(false);
    
    /**
     * 读锁
     */
    private static ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    
    /**
     * 写锁
     */
    private static ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
    
    public static void main(String[] args) {
        ReadWriteLock11Day lock11Day = new ReadWriteLock11Day();
        new Thread(() -> {
            lock11Day. read();
        }, "线程1").start();
        new Thread(() -> {
            lock11Day. read();
        }, "线程2").start();
        new Thread(() -> {
            lock11Day. write();
        }, "线程3").start();
        new Thread(() -> {
            lock11Day. write();
        }, "线程4").start();
        new Thread(() -> {
            lock11Day.read();
        }, "线程5").start();
    }
    
    private void read() {
        readLock.lock();
        try {
            System.out.println("当前："+Thread.currentThread().getName()+"正在执行（读锁）");
        } finally {
            readLock.unlock();
        }
    }
    
    private void write() {
        writeLock.lock();
        try {
            Thread.sleep(1000);
            System.out.println("当前："+Thread.currentThread().getName()+"正在执行（写锁）");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }
}
